package com.example.demo.config;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AbstractMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.annotation.Resource;

@Component
public class RedisChatMemory implements ChatMemory {
    Logger logger = LoggerFactory.getLogger(RedisChatMemory.class);
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void add(String conversationId, List<Message> messages) {
        ObjectMapper objectMapper = new ObjectMapper();
        messages.forEach(message -> {
            try {
                stringRedisTemplate.opsForList().leftPush(conversationId,
                        objectMapper.writeValueAsString(message));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        List<String> messages = stringRedisTemplate.opsForList().range(conversationId, 0, lastN - 1);
        List<Message> list = new ArrayList<>();
        messages.forEach(
                message -> {
                    try {
                        ObjectMapper objectMapper = new ObjectMapper();
                        AbstractMessage value = objectMapper.readValue(message, AbstractMessage.class);
                        list.add(value);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
        return list;
    }

    @Override
    public void clear(String conversationId) {
        return;
    }

}
